package cn.afactory.tygz.ui.base.views;

import android.app.Dialog;
import android.content.Context;
import android.os.Handler;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.RelativeLayout;

import com.lidroid.xutils.util.LogUtils;
import com.nostra13.universalimageloader.utils.ImageLoaderUtil;

import cn.afactory.tygz.R;
import cn.afactory.tygz.model.AdInfo;
import cn.afactory.tygz.model.AdInfoList;
import cn.afactory.tygz.ui.base.entity.BannerInfo;
import cn.afactory.tygz.ui.base.entity.BannerInfoList;
import cn.afactory.tygz.ui.base.utils.DialogUtil;
import cn.afactory.tygz.ui.base.utils.ImageUtils;
import cn.afactory.tygz.ui.base.utils.LoadingDialog;
import cn.afactory.tygz.ui.base.views.viewpagerindicator.CirclePageIndicator;


public class BannerView extends RelativeLayout {

	private static final int TIME = 4000;

	private WrapContentHeightViewPager mViewPager;
	private CirclePageIndicator mBannerDot;
    private ViewpagerAdapter mViewpagerAdapter;
    private AdInfoList mBannerInfoList;

	private int mCurrentid = 0;
	private boolean slideFlage = true;
	private Context mContext;
	
	private boolean isInfiniteLoop = true;
	
//	public BitmapUtils mNewBannerBitmapUtils;
	
	private boolean mLoadToListener = false;
	
//	private int mSelectIndex = 1000;

	public BannerView(Context paramContext) {
		super(paramContext);
	}

	public BannerView(Context context, AttributeSet attrs, AdInfoList infolist) {
		super(context, attrs);
		if (isInEditMode())
			return;
		this.mContext = context;
		this.mBannerInfoList = infolist;
//		mNewBannerBitmapUtils = BitmapHelp.getProfileUtils(mContext.getApplicationContext());

		init(context, attrs);
		
		showBanner();
	}

	public void setOnBannerClickListener(OnBannerClickListener onBannerClickListener){
		if ( null != mViewpagerAdapter) {
			mViewpagerAdapter.setOnBannerClickListener(onBannerClickListener);
		}
	}

	public void init(Context context, AttributeSet attrs) {
		LayoutInflater lf = LayoutInflater.from(mContext);
		lf.inflate(R.layout.banner_layout_new, this, true);

		//获取缓存
//		getCache();
		
		mViewPager = (WrapContentHeightViewPager) findViewById(R.id.banner_view_pager);
		mBannerDot = (CirclePageIndicator) findViewById(R.id.banner_dot);

		// 显示标题右边的 圆点

		mViewpagerAdapter = new ViewpagerAdapter(mContext);
		mViewpagerAdapter.setInfiniteLoop(isInfiniteLoop);
		mViewPager.setAdapter(mViewpagerAdapter);
		
		mBannerDot.setViewPager(mViewPager);
		mBannerDot.setInfiniteLoop(isInfiniteLoop);
		
		mViewPager.setOnPageChangeListener(new OnPageChangeListener() {

            @Override
            public void onPageSelected(int position) {
                mCurrentid = position;
                mBannerDot.setCurrentItem(mCurrentid);
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {

            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
                if (arg0 == 1) {
                    slideFlage = false;
                } else {
                    slideFlage = true;
                }
            }
        });
		
		setListener();
	}

	public void setBannerList(AdInfoList info) {

		mBannerInfoList = info;
		mLoadToListener = false;
		showBanner();
	}
	
	public void setBannerListNotSaveDB(AdInfoList info) {

		mBannerInfoList = info;
		mLoadToListener = false;
		showBanner();
	}
	
	private class ViewpagerAdapter extends AKCirclePageAdapter<AdInfo> {

		private OnBannerClickListener onBannerClickListener;
        public ViewpagerAdapter(Context c) {
            super(c);
        }

		public void setOnBannerClickListener(OnBannerClickListener onBannerClickListener) {
			this.onBannerClickListener = onBannerClickListener;
		}

        @Override
        public Object instantiateItem(ViewGroup container, final int position) {
            ImageView imageView = (ImageView) mInflater.inflate(
                    R.layout.riv_image_hall, null);
            imageView.setScaleType(ScaleType.CENTER_CROP);
//
//			Drawable drawable = mContext.getResources().getDrawable(R.drawable.ground_banner_moren);
//			BitmapDisplayConfig bc = new BitmapDisplayConfig();
//			bc.setLoadFailedDrawable(drawable);
//            bc.setLoadingDrawable(drawable);
//
//			mNewBannerBitmapUtils.display(imageView, ImageUtils.getImageFullUrl(
//					mData.get(position % mData.size()).imgUrl), bc);
//			ImageLoaderUtil.loadImage(mContext, imageView, ImageUtils.getThumbnailFullPath(mData
//                    .get(position % mData.size()).imgUrl, "720x200"), R.drawable.ground_banner_moren, R.drawable.ground_banner_moren);
            ImageLoaderUtil.loadImage(mContext, imageView, mData.get(position % mData.size()).iconPath, R.drawable.ground_banner_moren, R.drawable.ground_banner_moren);
			LogUtils.i(mData.get(position % mData.size()).iconPath);
//            mNewBannerBitmapUtils.display(imageView, ImageUtils.getThumbnailFullPath(mData
//                    .get(position % mData.size()).imgUrl,"720x200"), bc, new CustomBitmapLoadCallBack());
            container.addView(imageView);

			imageView.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					if (null != onBannerClickListener) {
						onBannerClickListener.onBannerClick(mData.get(position % mData.size()));
					}
				}
			});

            return imageView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            if (object instanceof View) {
                container.removeView((View) object);
            }
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }

    }
	
	
    Runnable runnable = new Runnable() {

        @Override
        public void run() {
            if (mViewpagerAdapter.getCount() > 0) {
                if (slideFlage) {
                    mCurrentid = (mCurrentid + 1 == mViewpagerAdapter.getCount() ? 0 : mCurrentid + 1);
                    mViewPager.setCurrentItem(mCurrentid, true);
                }
            }
            handler.postDelayed(this, TIME);
        }
    };

    Handler handler = new Handler();
    
    /*private void getCache() {
		if (mBannerInfoList != null && mBannerInfoList.value != null
				&& mBannerInfoList.value.size() > 0) {
//			showBanner();
		} else {
//			initBanner();
			//network request 
		}
    	
    }*/
    
    private void showBanner() {
//    	stopHandle();
//    	startHandle();
    	mViewpagerAdapter.clearItems();
		if (mBannerInfoList != null && mBannerInfoList.value != null
				&& mBannerInfoList.value.size() > 0) {
			mBannerDot.setCount(mBannerInfoList.value.size());
			if(mBannerInfoList.value.size() == 1) {
				mBannerDot.setVisibility(View.INVISIBLE);
			} else {
				mBannerDot.setVisibility(View.VISIBLE);
			}
	        for (int i = 0; i < mBannerInfoList.value.size(); i++) {
	        	mViewpagerAdapter.addItem(mBannerInfoList.value.get(i));
	        }
		} else if (mBannerInfoList == null || mBannerInfoList.value == null ||
				mBannerInfoList.value.size() == 0){
				mBannerDot.setVisibility(View.INVISIBLE);
		}

        mViewpagerAdapter.notifyDataSetChanged();
        
        if(mViewpagerAdapter.getData().size() > 0) {
        	mViewPager.setAdapter(mViewpagerAdapter);
        	mViewPager.setCurrentItem(mViewpagerAdapter.getData().size() * 300);
        }
    }; 
    
    private int xpos = 0 , ypos = 0;
    private long time;
    
    public void setListener(){
    	if(mLoadToListener) return;
    	
    	if(mViewPager != null) {
    		mViewPager.setOnTouchListener(new OnTouchListener() {
    			
    			@Override
    			public boolean onTouch(View v, MotionEvent event) {
    				switch (event.getAction()) {
    				case MotionEvent.ACTION_DOWN:
    					xpos = (int)event.getX();
    					ypos = (int)event.getY();
    					time = System.currentTimeMillis();
    					break;
    				case MotionEvent.ACTION_UP:
    					int tmpx = (int)event.getX() - xpos;
    					int tmpy = (int)event.getY() - ypos;
    					if(Math.abs(tmpx) < 10 && Math.abs(tmpy) < 10
    							&& Math.abs(time - System.currentTimeMillis()) < 1500){
    						myClick();
    					}
    					
    					break;
    				default:
    					break;
    				}
    				return false;
    			}
    		});
    	}
    	mLoadToListener = true;
    }

    private void myClick(){
		if (mViewpagerAdapter.getData().size() > 0) {

			int position = isInfiniteLoop ? mViewPager.getCurrentItem() % mViewpagerAdapter.getData().size() : mViewPager
					.getCurrentItem();
			if (position >= 0 && mBannerInfoList.value != null && mBannerInfoList.value.size() > position) {

				AdInfo tmp = mBannerInfoList.value.get(position);
				
//				if(true) {
//					Intent intent = new Intent();
//	                intent.setAction(SchemeItem.ACITVITY_ACTION);
//	                SchemeItem mItem = new SchemeItem(tmp.content, tmp.contentType);
//	                intent.putExtra(SchemeItem.EXTRA, mItem);
//	                try {
//	                	mContext.startActivity(intent);
//	                } catch (Exception e) {
//	                	LogUtils.e(e.toString(), e);
//	                }
//	                return;
//				}
//
//				if (getType(tmp.contentType) == ContentType.TYPE_LINK) {
//
//					if (TextUtils.isEmpty(tmp.content)) {
//						return;
//					}
//					Intent intent = new Intent(mContext, WebViewActivity.class);
//					intent.putExtra("web_url", tmp.content);
//					LogUtils.e(tmp.content);
//					intent.putExtra("title", "");
//					mContext.startActivity(intent);
//					return;
//				}
//
//				long postid = Long.valueOf(tmp.content);
//
//				switch (getType(tmp.contentType)) {
//				case ContentType.TYPE_FORUM:
//					Intent it = new Intent(mContext, HealthSquareDetailActivity.class);
//					it.putExtra(HealthSquareDetailActivity.EXTRA_DES, postid);
//					mContext.startActivity(it);
//					break;
//				case ContentType.TYPE_GROUP:
//					if (tmp.name != null && postid > 0) {
//						try {
//							GroupDO mGroupDO = DBManager.getDefaultDbUtils(mContext).findFirst(
//									Selector.from(GroupDO.class).where(WhereBuilder.b("group_id", "=", postid)));
//							if (mGroupDO == null) {
//								getIsFullWithGroup(postid, tmp.name);
//							} else {
//								HealthSquareForumDetailActivity.StartChat(mContext, postid, mGroupDO.name, 0);
//							}
//						} catch (Exception e) {
//							e.printStackTrace();
//						}
//					}
//
//					break;
//				case ContentType.TYPE_CLINIC:
//					startDoctorDetailActivity(postid);
//					break;
//				default:
//					break;
//				}
			}

		}
    }
    
	private LoadingDialog loadingDialog;

    public void showLoadingDialog(String msg) {
        if (loadingDialog == null) {
            loadingDialog = DialogUtil.showLoadingDialog(mContext, msg, true);
        }

        loadingDialog.setDlgMessage(msg);

        if (!loadingDialog.isShowing()) {
            loadingDialog.show();
        }
    }

    public void hideLoadingDialog() {
        if (loadingDialog != null && loadingDialog.isShowing()) {
            loadingDialog.dismiss();
        }
    }
	
	public void stopHandle(){
		handler.removeCallbacks(runnable);
	}
	
	public void startHandle(){
		handler.postDelayed(runnable, TIME);
	}
	
	private long mjoinposts = -1;
	private String mjoinname ;
	private boolean netIsFullWithGroup = false;
	
	private void getIsFullWithGroup(long postsId, String name) {
		if (netIsFullWithGroup) {
			return;
		}
		
		showLoadingDialog("");
		
		mjoinposts = postsId;
		mjoinname = name;
		netIsFullWithGroup = true;
		
		mjoinposts = postsId;
		mjoinname = name;
	}
	
    private Dialog retrydialog = null;
	
	private void showRetryDialog(Context ctx) {
//		retrydialog = com.pingan.papd.utils.DialogUtil.showMessageDialog(
//				ctx,
//				String.format(mContext.getString(R.string.square_join_gorup_title)),
//				getResources().getString(R.string.banner_group), mContext.getString(R.string.app_ok), mContext.getString(R.string.app_cancel),
//				new OnClickListener() {
//					@Override
//					public void onClick(View view) {
//						doJoinGroup(mjoinposts);
//						if (retrydialog != null && retrydialog.isShowing()) {
//							retrydialog.dismiss();
//							retrydialog = null;
//						}
//					}
//				}, new OnClickListener() {
//					@Override
//					public void onClick(View view) {
//						if (retrydialog != null && retrydialog.isShowing()) {
//							retrydialog.dismiss();
//							retrydialog = null;
//						}
//					}
//				});
//		if (!retrydialog.isShowing() && retrydialog != null) {
//			retrydialog.show();
//		}
	}

	public interface OnBannerClickListener {
		void onBannerClick(AdInfo adInfo);
	}
}
